//
//  HomeViewController.m
//  SafPay
//
//  Created by 贺庆博 on 2018/6/19.
//  Copyright © 2018年 ebo. All rights reserved.
//

#import "HomeViewController.h"
#import "UIButton+Layout.h"
#import "HomeViewCell.h"
#import "CustomerController.h"
#import "SettingViewController.h"
#import "WalletDetailsController.h"
#import "WalletModel.h"
#import "WalletCoinListModel.h"
#import "ChoseCoinController.h"
#import "CopySafeWordController.h"
#import "WJTools.h"
#import "XXLinkLabel.h"
@interface HomeViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    
    UILabel *moneyLab;
    UIButton *showBtn;
    UILabel *subLab;
    BOOL isHide;
}
@property (nonatomic , strong)dispatch_source_t timer;
@property (strong,nonatomic) UITableView *tableView;
@property (strong,nonatomic) UILabel *bottomView;
@property (strong,nonatomic) UIImageView *headerView;
@property (strong,nonatomic) UIButton *footerView;
@property (strong,nonatomic) NSMutableArray *arrDS;
@property (strong,nonatomic) TRRequest *request;
@property (strong,nonatomic) WalletModel *currentModel;
@end

@implementation HomeViewController
//- (void)viewWillAppear:(BOOL)animated
//{
//    [super viewWillAppear:animated];
//    [self.navigationController setNavigationBarHidden:YES animated:YES];
//}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    [self initNav];
    [self getNetWork];
    [self startTimer];
    

    // Do any additional setup after loading the view from its nib.
}
-(void)viewDidAppear:(BOOL)animated{
    
    if([AccountTools shared].currentAccount.isCopy){
        
        [self.bottomView setHidden:YES];
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.timer) {
        [self startTimer];
        
    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.timer) {
        dispatch_cancel(self.timer);
        
    }
}
- (void)initNav
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kNavHeight)];
    [self.view addSubview:view];
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, kNavHeight - 37, 30, 30)];
    [leftBtn setImage:kImageName(@"icon_customer") forState:UIControlStateNormal];
    [[leftBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        CustomerController *vc = [CustomerController new];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    [view addSubview:leftBtn];
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(kScreenWidth - 45, kNavHeight - 37, 30, 30)];
    [rightBtn setImage:kImageName(@"icon_setting") forState:UIControlStateNormal];
    [[rightBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        SettingViewController *vc = [SettingViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    [view addSubview:rightBtn];

    UILabel *titleLab = [UILabel labelWithFrame:CGRectMake(0, 0, 200, 20) font:kFONT(17) color:[UIColor whiteColor] text:@"管家云银包"];
    titleLab.yzCenterX = kScreenWidth/2;
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.yzCenterY = leftBtn.yzCenterY;
    [view addSubview:titleLab];

}
- (void)initUI
{
    UIImageView *img = [UIImageView new];
    img.image = kImageName(@"icon_bg");
    [self.view addSubview:img];
    [self.view addSubview:self.headerView];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.footerView];
    if([AccountTools shared].currentAccount.isCopy){
        
        [self.bottomView setHidden:YES];
    }
    [img mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.left.equalTo(self.view);
        make.top.equalTo(self.view).offset(0);
    }];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(self.view);
        make.height.mas_equalTo(40);
    }];
    [self.footerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.bottomView.mas_top).mas_offset(-10);
        make.left.equalTo(self.view).offset(22);
        make.right.equalTo(self.view).offset(-22);
        make.height.mas_equalTo(44);
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(22);
        make.right.equalTo(self.view).offset(-22);
        make.top.mas_equalTo(self.headerView.mas_bottom);
        make.bottom.mas_equalTo(self.footerView.mas_top).mas_offset(-10);
    }];
}
//定时器轮询
- (void)startTimer
{
    //获得队列
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    //创建一个定时器
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    //设置开始时间
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC));
    //设置时间间隔
    uint64_t interval = (uint64_t)([GTimeLength floatValue] * NSEC_PER_SEC);
    //设置定时器
    dispatch_source_set_timer(self.timer, start, interval, 0);
    //设置回调
    dispatch_source_set_event_handler(self.timer, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            UIApplicationState state = [UIApplication sharedApplication].applicationState;
            if (state == UIApplicationStateActive){
                [self getNetWork];
            };
        });
    });
    //启动定时器
    dispatch_resume(self.timer);
}


-(void)getNetWork{
    
 
    NSString *path=[NSString stringWithFormat:@"%@%@",kBaseUrl,kMyProperty];
    NSMutableDictionary *dict=[NSMutableDictionary new];
    [dict setValue:[AccountTools shared].currentAccount.userId forKey:@"uid"];
    [dict setValue:[AccountTools shared].currentAccount.token forKey:@"token"];
    [self.request Post:path parameters:dict success:^(TRRequest *request, NSDictionary *responseDict) {
        
        
        
        if([[responseDict valueForKey:@"error"] integerValue]==0){
            
            self.currentModel=[WalletModel yy_modelWithDictionary:responseDict];
            self->moneyLab.text = self->showBtn.selected?@"****":[NSString stringWithFormat:@"¥ %@",self.currentModel.count_cny];
            [self.tableView reloadData];
            
        }
//        else{
//
//            [MBProgressHUD showErrorWithText:[responseDict valueForKey:@"error_msg"]];
//        }
        MyLog(@"%@",responseDict);
    
    } failure:^(TRRequest *request, NSError *error) {
        
        
    }];
}
-(void)addCoinByNewWork:(CoinListModel*)coinModel{
    
    NSString *path=[NSString stringWithFormat:@"%@%@",kBaseUrl,kCoinAdd];
    NSMutableDictionary *dict=[NSMutableDictionary new];
    [dict setValue:[AccountTools shared].currentAccount.userId forKey:@"uid"];
    [dict setValue:[AccountTools shared].currentAccount.token forKey:@"token"];
    [dict setValue:coinModel.cid forKey:@"cid"];
    [dict setValue:coinModel.name forKey:@"coinname"];
    [self.request Post:path parameters:dict success:^(TRRequest *request, NSDictionary *responseDict) {
        
        
        
        if([[responseDict valueForKey:@"error"] integerValue]==0){
            
            [MBProgressHUD showSuccessWithText:[responseDict valueForKey:@"error_msg"]];
            [self getNetWork];
            
        }else{
            
            [MBProgressHUD showErrorWithText:[responseDict valueForKey:@"error_msg"]];
        }
        MyLog(@"%@",responseDict);
        
    } failure:^(TRRequest *request, NSError *error) {
        
        [MBProgressHUD showErrorWithText:@"网络请求失败！"];
    }];
    
}
-(void)addCoinClick{
    
    ChoseCoinController *vc=[ChoseCoinController new];
    vc.isAdd=YES;
    vc.isHaveCoinArr=self.currentModel.data;
    vc.coinClickBlock = ^(CoinListModel *model) {
        
        [self addCoinByNewWork:model];
    };
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)tapClick{
    
    CopySafeWordController *vc=[CopySafeWordController new];
    vc.keyWord=[AccountTools shared].currentAccount.keyWord;
    vc.isHome=YES;
    [self.navigationController pushViewController:vc animated:YES];
    
}
#pragma mark - Lazy
-(TRRequest *)request{
    
    if(!_request){
        
        _request=[TRRequest request];
    }
    return _request;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.rowHeight = 69;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"HomeViewCell" bundle:nil] forCellReuseIdentifier:@"HomeViewCell"];
    }
    return _tableView;
}
- (UILabel *)bottomView
{
    if (!_bottomView) {
        
    
        _bottomView=[[TRUIFactory factory]createLabelWithText:nil Font:nil TextColor:nil];
        _bottomView.textAlignment = NSTextAlignmentCenter;
        [_bottomView setUserInteractionEnabled:YES];
        UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick)];
        UIImage *img = [UIImage imageNamed:@"icon_waring"];
        NSTextAttachment *textAttach = [[NSTextAttachment alloc]init];
        textAttach.image = img;
        textAttach.bounds = CGRectMake(-5, -5, 20, 20);
        NSAttributedString *imgStr = [NSAttributedString attributedStringWithAttachment:textAttach];
         NSMutableAttributedString *str=[WJTools changeLabelWithText:@"未备份钱包存在风险，请立即备份 >" withChangeText:@"立即备份 >" withFont:kFONT(14) color:rgb(230,46,46)];
        
        NSRange range = [str.string rangeOfString:@"未备份钱包存在风险，请"];
        [str addAttribute:NSForegroundColorAttributeName value:kGrayColor range:range];
        [str addAttribute:NSFontAttributeName value:kFONT(14) range:range];
        [str insertAttributedString:imgStr atIndex:0];
        
        [_bottomView setAttributedText:str];
        [_bottomView addGestureRecognizer:tap];
        
    }
    return _bottomView;
}
- (UIImageView *)headerView
{
    if (!_headerView) {
        _headerView = [[UIImageView alloc]initWithFrame:CGRectMake(4, kNavHeight + 18, kScreenWidth - 8, 206)];
        _headerView.image = kImageName(@"icon_card");
        _headerView.userInteractionEnabled = YES;
//        _headerView.backgroundColor = [UIColor whiteColor];
        showBtn = [UIButton new];
        [showBtn setImage:kImageName(@"icon_show") forState:UIControlStateNormal];
        [showBtn setImage:kImageName(@"icon_hidden") forState:UIControlStateSelected];

       moneyLab = [UILabel labelWithFont:kFONT(33) color:rgb(55,166,212) text:[NSString stringWithFormat:@"¥ %@",self.currentModel.count_cny]];
        [[showBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            self->showBtn.selected = !self->showBtn.selected;
            self->moneyLab.text = self->showBtn.selected?@"****":[NSString stringWithFormat:@"¥ %@",self.currentModel.count_cny];
            self->isHide=self->showBtn.selected;
            [self.tableView reloadData];
        }];
        moneyLab.textAlignment = NSTextAlignmentCenter;
        
        UIButton *guzhiBtn = [UIButton new];
        [guzhiBtn setTitle:@"总资产估值" forState:UIControlStateNormal];
        guzhiBtn.titleLabel.font = kFONT(14);
        [guzhiBtn setTitleColor:rgb(153,153,153) forState:UIControlStateNormal];
        guzhiBtn.layer.cornerRadius = 12;
        guzhiBtn.layer.borderColor = rgb(153,153,153).CGColor;
        guzhiBtn.layer.borderWidth = 1;
        
        subLab = [UILabel labelWithFont:kFONT(13) color:rgb(117,117,117) text:@"刚刚更新\n..."];
        subLab.numberOfLines = 0;
        subLab.textAlignment = NSTextAlignmentCenter;
        __weak typeof (UIView *)weakHeader = _headerView;
        [_headerView addSubview: showBtn];
        [_headerView addSubview: moneyLab];
        [_headerView addSubview: guzhiBtn];
        [_headerView addSubview: subLab];
        [showBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(weakHeader).offset(-40);
            make.top.equalTo(weakHeader).offset(20);
        }];
        
        [moneyLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(weakHeader);
            make.top.equalTo(weakHeader).offset(59);
        }];
        
        [guzhiBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(100);
            make.height.mas_equalTo(25);
            make.centerX.equalTo(weakHeader);
            make.top.mas_equalTo(self->moneyLab.mas_bottom).mas_offset(16);
        }];
        
        [subLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(weakHeader);
            make.bottom.equalTo(weakHeader).offset(-16);
        }];
    }
    return _headerView;
}
- (UIButton *)footerView
{
    if (!_footerView) {
        _footerView = [UIButton buttonWithType:UIButtonTypeCustom];
        _footerView.layer.cornerRadius = 3;
        _footerView.layer.borderColor = rgb(153,153,153).CGColor;
        _footerView.titleLabel.font = kFONT(16);
        _footerView.layer.borderWidth = 1;
        [_footerView setTitleColor:rgb(95,96,96) forState:UIControlStateNormal];
        [_footerView setTitle:@"添加其它币种" forState:UIControlStateNormal];
        [_footerView setImage:kImageName(@"icon_add") forState:UIControlStateNormal];
        [_footerView sc_setLayoutStyle:SCButtonLayoutStyleImageLeft spacing:5];
        [_footerView addTarget:self action:@selector(addCoinClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _footerView;
}
-(WalletModel *)currentModel{
    
    if(!_currentModel){
        
        _currentModel=[WalletModel new];
        _currentModel.count_cny=@"--";
    }
    return _currentModel;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //return self.currentModel.data.count;
    return 3;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HomeViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeViewCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    WalletCoinListModel *model=[self.currentModel.data objectAtIndex:indexPath.section];
   // [cell setModel:model withStatus:isHide];
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 12)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 12;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return .00000001f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WalletCoinListModel *model=[self.currentModel.data objectAtIndex:indexPath.section];
    WalletDetailsController *vc = [WalletDetailsController new];
    vc.coinname=model.coin_name;
    vc.wid=model.wid;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
